package com.foruo.learn.designmode.chain.servlet;

import com.foruo.learn.designmode.chain.servlet.entity.MyRequest;
import com.foruo.learn.designmode.chain.servlet.entity.MyResponse;
import com.foruo.learn.designmode.chain.servlet.filter.FirstFilter;
import com.foruo.learn.designmode.chain.servlet.filter.SecondFilter;
import com.foruo.learn.designmode.chain.servlet.filter.ThirdFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * 过滤器链
 * @author GaoYuan
 * @date 2018/10/30 下午1:11
 */
public class FilterChain implements IFilterChain{

    /** 存储所有的filter */
    private List<IFilter> filterList = new ArrayList<>();
    /** 当前执行的filter的下标索引 */
    private int index = 0;

    public FilterChain(){
        // 构造函数，调用初始化
        init();
    }

    /**
     * 初始化三个过滤器
     * 当然也可以写个方法，提供自定义过滤器的添加入口
     */
    public FilterChain init(){
        filterList.add(new FirstFilter());
        filterList.add(new SecondFilter());
        filterList.add(new ThirdFilter());
        index = 0;
        return this;
    }

    /**
     * 执行
     */
    @Override
    public void doFilter(MyRequest myRequest, MyResponse myResponse){
        if(filterList.size() > index){
            filterList.get(index ++).doFilter(myRequest, myResponse, this);
        }
    }

}
